package hikari.script.compiler;

import com.gooddies.wiring.annotations.Wire;
import com.gooddies.wiring.annotations.WiringComponent;
import hikari.script.ScriptFile;
import hikari.utils.Utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author sad
 */
@WiringComponent
public class VS8Compiler {

    private String baseFolder;
    private final static String MEDIA_PREFIX = "../../media/";
    @Wire
    private Utils utils;

    public void setBaseFolder(String baseFolder) {
        this.baseFolder = utils.combinePaths(baseFolder, "project");
    }

    private NodeList execXPath(Document doc, String expression) throws XPathExpressionException {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile(expression);
        NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        return nl;
    }

    private Document openXMLDocument(String path) throws SAXException, IOException, ParserConfigurationException {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        return dBuilder.parse(path);
    }

    private void saveXMLDocument(String path, Document doc) throws SAXException, IOException, ParserConfigurationException, TransformerConfigurationException, TransformerException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);
    }

    private String nodeToFileName(Node node) {
        return ((Element) node).getAttribute("Include");
    }

    private List<String> nodeListToFileNameList(NodeList list) {
        List<String> lst = new ArrayList<>();
        for (int i = 0; i < list.getLength(); i++) {
            lst.add(nodeToFileName(list.item(i)));
        }
        return lst;
    }

    /**
     * @return if some changes maked, returns true
     */
    private boolean synchronizeFiles(Document doc, List<String> findedFiles, String xpath, String tagName) throws XPathExpressionException {
        NodeList nodes = execXPath(doc, xpath);
        Node parentNode = nodes.item(0).getParentNode();
        List<String> paths = nodeListToFileNameList(nodes);
        filterCustomUserFiles(paths);
        subtractLists(findedFiles, paths);
        subtractLists(paths, findedFiles);
        if (!findedFiles.isEmpty()) {
            addFilesToProject(doc, findedFiles, parentNode, tagName);
            return true;
        }
        return false;
    }

    private void addFilesToProject(Document doc, List<String> findedFiles, Node parentNode, String tagName) {
        for (String file : findedFiles) {
            file = MEDIA_PREFIX + file;
            Element element = doc.createElement(tagName);
            element.setAttribute("Include", file);
            parentNode.appendChild(element);
        }
    }

    public static void subtractLists(List<String> listWhere, List<String> listWhat) {
        for (int j = 0; j < listWhat.size(); j++) {
            String line = listWhat.get(j).toLowerCase();
            for (int i = 0; i < listWhere.size(); i++) {
                if (listWhere.get(i).toLowerCase().equals(line)) {
                    listWhere.remove(i);
                    i--;
                }
            }
        }
    }

    /**
     * method leaves only files that starts with ../../media
     */
    private void filterCustomUserFiles(List<String> files) {
        for (int i = 0; i < files.size(); i++) {
            if (!files.get(i).toLowerCase().startsWith(MEDIA_PREFIX)) {
                files.remove(i);
                i--;
            } else {
                String path = files.get(i);
                path = path.substring(MEDIA_PREFIX.length());
                files.set(i, path);
            }
        }
    }

    private List<String> getListOfIncludeFiles(List<ScriptFile> scriptFiles) {
        List<String> files = new ArrayList<>();
        for (ScriptFile script : scriptFiles) {
            files.add(script.getPath());
        }
        return files;
    }

    private List<String> getListOfCppFiles(List<ScriptFile> scriptFiles) {
        List<String> files = new ArrayList<>();
        for (ScriptFile script : scriptFiles) {
            String path = script.getLinkedCPPFile();
            if (path != null && !path.isEmpty()) {
                files.add(path);
            }
        }
        return files;
    }

    public void synchronizeProjectWithListOfScript(List<ScriptFile> scriptFiles) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformerConfigurationException, TransformerException {
        String projectFilePath = utils.combinePaths(baseFolder, "project.vcxproj");
        Document doc = openXMLDocument(projectFilePath);
        boolean result1 = synchronizeFiles(doc, getListOfIncludeFiles(scriptFiles), "/Project/ItemGroup/ClInclude", "ClInclude");
        boolean result2 = synchronizeFiles(doc, getListOfCppFiles(scriptFiles), "/Project/ItemGroup/ClCompile", "ClCompile");
        if (result1 || result2) {
            saveXMLDocument(projectFilePath, doc);
        }
    }
}
